﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NotebookS2.Manufacturing.Transactions
{
    public partial class ProductionOrder : Form
    {

        
        public DataTable GetOrderTable()
        {
            DataTable dt = new DataTable();

            dt.Columns.Add("ItemCode", typeof(string));
            dt.Columns.Add("ItemDesc", typeof(string));
            dt.Columns.Add("UoM", typeof(string));
            dt.Columns.Add("Qty", typeof(double));
            dt.Columns.Add("DateNeeded", typeof(DateTime));

            return dt;

        }

        void RemoveBlankLastRowFirst()
        {
            gridView1.MoveLast();
            try
            {


                int iCount = gridView1.FocusedRowHandle;;
                string sItemCode = "";


                sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                if (sItemCode.Trim() == "")
                {
                    gridView1.DeleteRow(iCount);
                }
            }
            catch { }

        }
        public DataTable OrderLineItems { get; set; }
        public ProductionOrder()
        {
            InitializeComponent();
        }

        public string ActiveUserID { get; set; }
        public string ConnectionString { get; set; }

        private void ProductionOrder_Load(object sender, EventArgs e)
        {
            this.OrderLineItems = GetOrderTable();

            gridControl1.DataSource = this.OrderLineItems;
            gridControl1.Refresh();

            gridView1.AddNewRow();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            SqlConnection oConnection = new SqlConnection();
            SqlCommand oCommand = new SqlCommand();
            SqlDataAdapter oAdapter = new SqlDataAdapter();

            RemoveBlankLastRowFirst();

            try
            {
                if (btnAdd.Text == "Add")
                {
                    oConnection.ConnectionString = this.ConnectionString;
                    oConnection.Open();

                    #region Adding of Production Order - ADD COMMAND SQL SCRIPT
                   
                    oCommand.Connection = oConnection;
                    oCommand.CommandText = "INSERT OPORDR (DocNum, RequestedBy, Remarks, DocStatus, DateCreated, CreatedBy, DateModified, ModifiedBy) VALUES  (@DocNum, @RequestedBy, @Remarks, @DocStatus, @DateCreated, @CreatedBy, @DateModified, @ModifiedBy)";
                    oCommand.Parameters.Add(new SqlParameter("@DocNum", txtDocNum.Text));
                    oCommand.Parameters.Add(new SqlParameter("@RequestedBy", txtRequestedBy.Text));
                    oCommand.Parameters.Add(new SqlParameter("@Remarks", txtRemarks.Text));
                    oCommand.Parameters.Add(new SqlParameter("@DocStatus", txtStatus.Text));
                    oCommand.Parameters.Add(new SqlParameter("@DateCreated", System.DateTime.Now));
                    oCommand.Parameters.Add(new SqlParameter("@CreatedBy", txtCreatedBy.Text));
                    oCommand.Parameters.Add(new SqlParameter("@DateModified", System.DateTime.Now));
                    oCommand.Parameters.Add(new SqlParameter("@ModifiedBy", txtCreatedBy.Text));

                    oCommand.ExecuteNonQuery();

                    btnAdd.Text = "Update";
                    #endregion



                    #region Adding Line Items - COMMAND SCRIPT

                    foreach (DataRow oRow in this.OrderLineItems.Rows)
                    {
                        if (oRow.RowState != DataRowState.Deleted)
                        {
                            oCommand = new SqlCommand();
                            oCommand.Connection = oConnection;

                            oCommand.CommandText = "INSERT PORDR1 (DocNum, ItemCode, ItemDesc, Qty, UoM, DateNeeded) VALUES (@DocNum, @ItemCode, @ItemDesc, @Qty, @UoM, @DateNeeded)";
                            oCommand.Parameters.Add(new SqlParameter("@DocNum", txtDocNum.Text));
                            oCommand.Parameters.Add(new SqlParameter("@ItemCode", oRow["ItemCode"].ToString()));
                            oCommand.Parameters.Add(new SqlParameter("@ItemDesc", oRow["ItemDesc"].ToString()));
                            oCommand.Parameters.Add(new SqlParameter("@Qty", oRow["Qty"].ToString()));
                            oCommand.Parameters.Add(new SqlParameter("@UoM", oRow["UoM"].ToString()));
                            oCommand.Parameters.Add(new SqlParameter("@DateNeeded", oRow["DateNeeded"].ToString()));

                            oCommand.ExecuteNonQuery();

                        }
                    }

                    #endregion

                    oConnection.Close();


                    MainMenu oForm = (MainMenu)this.MdiParent;


                    btnRunMRP.Enabled = true;
                    btnPreparePR.Enabled = true;

                    oForm.ErrMsg.ImageIndex = 8;
                    oForm.ErrMsg.Caption = "Successfully added!!!";
                    oForm.timer1.Enabled = true;
                }
                else
                {
                    if (txtStatus.Text == "Draft")
                    {
                        oConnection.ConnectionString = this.ConnectionString;
                        oConnection.Open();

                        #region Updating Production Order - HEADER DATA
                        oCommand.Connection = oConnection;
                        oCommand.CommandText = "UPDATE OPORDR RequestedBy=@RequestedBy, Remarks=@Remarks, DocStatus=@DocStatus, DateModified=@DateModified, ModifiedBy=@ModifiedBy WHERE DocNum = @DocNum";

                        oCommand.Parameters.Add(new SqlParameter("@DocNum", txtDocNum.Text));
                        oCommand.Parameters.Add(new SqlParameter("@RequestedBy", txtRequestedBy.Text));
                        oCommand.Parameters.Add(new SqlParameter("@Remarks", txtRemarks.Text));
                        oCommand.Parameters.Add(new SqlParameter("@DocStatus", txtStatus.Text));
                        oCommand.Parameters.Add(new SqlParameter("@DateCreated", System.DateTime.Now));
                        oCommand.Parameters.Add(new SqlParameter("@CreatedBy", txtCreatedBy.Text));

                        oCommand.ExecuteNonQuery();

                        #endregion


                        #region Delete Existing Line Item 
                        
                        oCommand = new SqlCommand();
                        oCommand.Connection = oConnection;

                        oCommand.CommandText = "DELETE FROM PORDR1 WHERE DocNum=@DocNum";
                        oCommand.Parameters.Add(new SqlParameter("@DocNum", txtDocNum.Text));
                        oCommand.ExecuteNonQuery();

                        #endregion

                        #region Insert the Updated Line Items - COMMAND SCRIPT


                        foreach (DataRow oRow in this.OrderLineItems.Rows)
                        {
                            if (oRow.RowState != DataRowState.Deleted)
                            {
                                oCommand = new SqlCommand();
                                oCommand.Connection = oConnection;

                                oCommand.CommandText = "INSERT PORDR1 (DocNum, ItemCode, ItemDesc, Qty, UoM, DateNeeded) VALUES (@DocNum, @ItemCode, @ItemDesc, @Qty, @UoM, @DateNeeded)";
                                oCommand.Parameters.Add(new SqlParameter("@DocNum", txtDocNum.Text));
                                oCommand.Parameters.Add(new SqlParameter("@ItemCode", oRow["ItemCode"].ToString()));
                                oCommand.Parameters.Add(new SqlParameter("@ItemDesc", oRow["ItemDesc"].ToString()));
                                oCommand.Parameters.Add(new SqlParameter("@Qty", oRow["Qty"].ToString()));
                                oCommand.Parameters.Add(new SqlParameter("@UoM", oRow["UoM"].ToString()));
                                oCommand.Parameters.Add(new SqlParameter("@DateNeeded", oRow["DateNeeded"].ToString()));

                                oCommand.ExecuteNonQuery();

                            }
                        }

                        #endregion
                        oConnection.Close();

                        MainMenu oForm = (MainMenu)this.MdiParent;

                        oForm.ErrMsg.ImageIndex = 8;
                        oForm.ErrMsg.Caption = "Successfully updated!!!";
                        oForm.timer1.Enabled = true;
                    }
                }
            }
            catch (SqlException ex)
            {
                MainMenu oForm = (MainMenu)this.MdiParent;

                oForm.ErrMsg.ImageIndex = 6;
                oForm.ErrMsg.Caption = ex.Message.ToString();
                oForm.timer1.Enabled = true;
            }
        }

        private void gridView1_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                int iCount = gridView1.FocusedRowHandle;


                if (e.KeyCode == Keys.Delete)
                {
                    if (txtStatus.Text == "Draft")
                    {
                        if (MessageBox.Show("Are you sure you want to delete this Row?", "Delete", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {

                            if (gridView1.IsLastRow)
                            {
                                string sItemCode = "";


                                iCount = gridView1.FocusedRowHandle;
                                sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();


                                if (sItemCode != "")
                                {
                                    gridView1.DeleteRow(iCount);
                                    gridView1.AddNewRow();
                                }


                                gridView1.RefreshData();

                            }
                            else
                            {


                                iCount = gridView1.FocusedRowHandle;

                                gridView1.DeleteRow(iCount);
                                gridView1.RefreshData();
                            }
                        }
                    }


                }

                if (e.KeyCode == Keys.Down)
                {
                    if (gridView1.IsLastRow)
                    {

                        string sItemCode = "";

                        iCount = gridView1.FocusedRowHandle;
                        sItemCode = gridView1.GetRowCellValue(iCount, gridView1.Columns["ItemCode"]).ToString();

                        if (sItemCode != "" && (txtStatus.Text == "Draft"))
                        {
                            gridView1.AddNewRow();

                            gridControl1.Select();
                            gridView1.FocusedRowHandle = DevExpress.XtraGrid.GridControl.NewItemRowHandle;
                            gridView1.FocusedColumn = gridView1.VisibleColumns[1];
                            gridView1.ShowEditor();


                        }

                        if (btnAdd.Text == "Ok" && txtStatus.Text == "Draft")
                        {
                            btnAdd.Text = "Update";
                        }
                    }
                }
            }
            catch
            {
            }
        }

        private void txtItemCode_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {

            FND_ITEM oForm = new FND_ITEM();

            oForm.ConnectionString = this.ConnectionString;
            oForm.ShowDialog();

            int iRowHandle = gridView1.FocusedRowHandle;

            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["ItemCode"], oForm.SelectedItemCode);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["ItemDesc"], oForm.SelectedItemDescription);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["UoM"], oForm.SelectedItemUnitMeasure);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["Qty"], 0);
            gridView1.SetRowCellValue(iRowHandle, gridView1.Columns["DateNeeded"], System.DateTime.Now);
        }

        private void btnRunMRP_Click(object sender, EventArgs e)
        {

        }

        private void ProductionOrder_Shown(object sender, EventArgs e)
        {
            txtCreatedBy.Text = this.ActiveUserID;
            txtModifiedBy.Text = this.ActiveUserID;
        }
    }
}
